package xyz.icxl.kotlion.ext.primitives

import android.icu.number.IntegerWidth
import com.blankj.utilcode.util.ConvertUtils
import kotlin.experimental.and


/**
 * 二进制数据转16进制字符串
 */
fun ByteArray.toHexString():String{
//    val stringBuilder = StringBuilder()
//    if (isEmpty()) {
//        return ""
//    }
//    for (i in 0 until size) {
//        val v: Byte = this[i] and 0xFF.toByte()
//        val hv = Integer.toHexString(v.toInt())
//        if (hv.length < 2) {
//            stringBuilder.append(0)
//        }
//        stringBuilder.append(hv)
//    }
//    return stringBuilder.toString()
    return ConvertUtils.bytes2HexString(this)
}

fun Byte.toHexStr():String{
    val stringBuilder = StringBuilder()
    val v: Byte = this and 0xFF.toByte()
    val hv = Integer.toHexString(v.toInt())
    if (hv.length < 2) {
        stringBuilder.append(0)
    }
    stringBuilder.append(hv)
    return stringBuilder.toString()
}

/**
 * 16进制数据美化
 */
fun String.hexStrBeautify():String{
    val sb = StringBuilder()
    this.forEachIndexed { index, c ->
        sb.append(c)
        if ((index+1) %2 == 0 && index !=2){
            sb.append("\t")
        }
    }
    return sb.toString()
}

/**
 * 字节转Bit数组
 */
fun Byte.toBitArray():IntArray{
    val bitArray = IntArray(8)
    bitArray[0] = this.toInt().shr(7) and 0x1
    bitArray[1] = this.toInt().shr(6) and 0x1
    bitArray[2] = this.toInt().shr(5) and 0x1
    bitArray[3] = this.toInt().shr(4) and 0x1
    bitArray[4] = this.toInt().shr(3) and 0x1
    bitArray[5] = this.toInt().shr(2) and 0x1
    bitArray[6] = this.toInt().shr(1) and 0x1
    bitArray[7] = this.toInt().shr(0) and 0x1
    return bitArray
}

/**
 * 字节数组 转Bit数组
 */
fun ByteArray.toBitArray():IntArray{
    if (size == 0)
        return IntArray(0)
    val bitArray = IntArray(size*8)
    for (i in 0 until size){
        get(i).toBitArray().forEachIndexed { index, v ->
            bitArray[index+(i*8)] = v
        }
    }
    return bitArray
}

/**
 * bit 转 Byte
 * 如
 */
fun String?.bitStr2Byte():Byte{
    var re = 0
    var len = 0
    if (this == null)
        return 0
    len = length
    if (len !=4 || len !=8)
        return 0
    re = if (len == 8){ // 8Bit 处理
        if (this[0] == '0'){//正数
            Integer.parseInt(this,2)
        }else{//负数
            Integer.parseInt(this,2)-256
        }
    }else{ //4 bit处理
        Integer.parseInt(this,2)
    }
    return re.toByte()
}